<template>
  <view>
    <!-- 顶部部分保持不变 -->
    <view class="uni-header">
      <view class="uni-group">
        <view class="uni-title">商品列表</view>
        <view class="uni-sub-title"></view>
      </view>
      <view class="uni-group">
        <input class="uni-search" type="text" v-model="query" @confirm="search" placeholder="请输入搜索内容" />
        <button class="uni-button" type="default" size="mini" @click="search">搜索</button>
        <button class="uni-button" type="default" size="mini" @click="addProduct">新增</button>
        <button class="uni-button" type="default" size="mini" :disabled="!selectedIds.length" @click="batchDelete">批量删除</button>
        <download-excel class="hide-on-phone" :fields="exportFields" :data="productList" :type="exportExcel.type" :name="exportExcel.filename">
          <button class="uni-button" type="primary" size="mini">导出 Excel</button>
        </download-excel>
      </view>
    </view>
    <!-- 修改表格部分 -->
    <view class="uni-container">
      <uni-table ref="table" :loading="loading" :emptyText="error.message || '没有更多数据'" border stripe type="selection" @selection-change="selectionChange">
        <uni-tr>
         
          <uni-th align="center" width="150" filter-type="search" @filter-change="filterChange($event, '_id')">ID</uni-th>
          <uni-th align="center" width="100" filter-type="search" @filter-change="filterChange($event, 'name')">名称</uni-th>
          <uni-th align="center" width="100">图片</uni-th>
          <uni-th align="center" filter-type="select" :filter-data="categoryOptions" @filter-change="filterChange($event, 'category_id')">基础分类</uni-th>
          <uni-th align="center" filter-type="select" :filter-data="specialCategoryOptions" @filter-change="filterChange($event, 'special_category_ids')">特殊分类</uni-th>
          <uni-th align="center" filter-type="range" @filter-change="filterChange($event, 'price')" sortable @sort-change="sortChange($event, 'price')">价格</uni-th>
          <uni-th align="center" filter-type="range" @filter-change="filterChange($event, 'discount_price')">折扣价格</uni-th>
          <uni-th align="center" filter-type="range" @filter-change="filterChange($event, 'points')">积分</uni-th>
          <uni-th align="center" filter-type="search" @filter-change="filterChange($event, 'description')">描述</uni-th>
          <uni-th align="center">操作</uni-th>
        </uni-tr>
        <uni-tr v-for="item in productList" :key="item._id">
          
          <uni-td align="center">
            <checkbox-group @change="(e) => selectItem(e, item._id)">
              <checkbox :value="item._id" :checked="selectedIds.includes(item._id)"/>
            </checkbox-group>
          </uni-td>
          <uni-td align="center">{{ item.data_id }}</uni-td>
          <uni-td align="center">{{ item.name }}</uni-td>
          <uni-td align="center">
            <image v-if="item.image" :src="item.image" style="width: 80rpx;height: 80rpx;border-radius: 8rpx" />
          </uni-td>
          <uni-td align="center">{{ getCategoryName(item.category_id) }}</uni-td>
          <uni-td align="center">{{ getSpecialCategoryNames(item.special_category_ids).join(', ') }}</uni-td>
          <uni-td align="center">{{ item.price }}</uni-td>
          <uni-td align="center">{{ item.discount_price }}</uni-td>
          <uni-td align="center">{{ item.points }}</uni-td>
          <uni-td align="center">{{ item.description }}</uni-td>
          <uni-td align="center">
            <view class="uni-group">
              <button @click="editProduct(item)" class="uni-button" size="mini" type="primary">修改</button>
              <button @click="deleteProduct(item)" class="uni-button" size="mini" type="warn">删除</button>
            </view>
          </uni-td>
        </uni-tr>
      </uni-table>
      <uni-fab 
        horizontal="right" 
        vertical="bottom"
        @fabClick="addProduct"
      />
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      productList: [],
      selectedIds: [],
      batchDeleteLoading: false,
      categoryOptions: [],
      specialCategoryOptions: [], // 新增特殊分类选项
      exportFields: {
        'ID': '_id',
        '名称': 'name',
        '缩略图': 'image',
        '所属基础分类': 'category_id',
        '所属特殊分类数组': 'special_category_ids',
        '价格': 'price',
        '折扣价格': 'discount_price',
        '积分': 'points',
        '描述': 'description'
      },
      query: '',
      exportExcel: {
        "filename": "商品列表.xls",
        "type": "xls",
        "fields": {
          'ID': '_id',
          '名称': 'name',
          '缩略图': 'image',
          '所属基础分类': 'category_id',
          '所属特殊分类数组': 'special_category_ids',
          '价格': 'price',
          '折扣价格': 'discount_price',
          '积分': 'points',
          '描述': 'description'
        }
      },
      loading: false,
      error: { message: '' },
      where: '',
      orderby: '',
      orderByFieldName: ""
    }
  },
  mounted() {
    this.loadProducts()
    this.loadCategories()
    this.loadSpecialCategories() // 新增加载特殊分类方法
  },
  methods: {
    search() {
      const newWhere = this.getWhere()
      this.where = newWhere
      this.$nextTick(() => {
        this.loadProducts()
      })
    },
    getWhere() {
      const query = this.query.trim()
      if (!query) {
        return ''
      }
      const queryRe = new RegExp(query, 'i')
      return ['_id', 'name', 'description'].map(name => queryRe + '.test(' + name + ')').join(' || ')
    },
    filterChange(e, field) {
      if (e.type === 'search') {
        this.where[field] = e.value
      } else if (e.type === 'select') {
        this.where[field] = e.value
      }
      this.loadProducts()
    },
    sortChange(e, field) {
      this.orderBy = e.order === 'asc' ? field + ' asc' : field + ' desc'
      this.loadProducts()
    },
    async loadProducts() {
      this.loading = true
      const db = uniCloud.database()
      try {
        const res = await db.collection('jl_products')
          .where(this.where)
          .orderBy(this.orderBy)
          .get()
        this.productList = res.data
        this.error.message = ''
      } catch (err) {
        this.error.message = err.message
      } finally {
        this.loading = false
      }
    },
    addProduct() {
      uni.navigateTo({
        url: '/pages/product/add/add'
      })
    },
    editProduct(item) {
      uni.navigateTo({
        url: `/pages/product/edit/edit?id=${item._id}`
      })
    },
    batchDelete() {
      this.batchDeleteLoading = true
      uniCloud.database().collection('jl_products')
        .where({
          _id: uniCloud.command.in(this.selectedIds)
        })
        .remove()
        .then(() => {
          this.loadProducts()
          this.selectedIds = []
        })
        .finally(() => this.batchDeleteLoading = false)
    },
    selectItem(e, id) {
      if (e.detail.value.length) {
        this.selectedIds.push(id)
      } else {
        this.selectedIds = this.selectedIds.filter(item => item !== id)
      }
    },
    async deleteProduct(item) {
      await uniCloud.database().collection('jl_products')
        .doc(item._id)
        .remove()
      this.loadProducts()
    },
    async loadCategories() {
      const res = await uniCloud.database().collection('jl_product_categories')
        .where({ type: '基础分类' })
        .get()
      this.categoryOptions = res.data.map(item => ({
        text: item.name,
        value: item.data_id
      }))
    },
    async loadSpecialCategories() {
      const res = await uniCloud.database().collection('jl_product_categories')
        .where({ type: '特殊分类' })
        .get()
      this.specialCategoryOptions = res.data.map(item => ({
        text: item.name,
        value: item.data_id
      }))
    },
    hasPermission(value) {
      return uni.getSystemInfoSync().uniAdmin.permission.includes(value)
    },
    async getCategoryName(categoryId) {
      const { data } = await uniCloud.database().collection('jl_product_categories')
        .doc(categoryId)
        .field('name')
        .get()
      return data[0]?.name || '未知分类'
    },
    async getSpecialCategoryNames(categoryIds) {
      const names = []
      for (const id of categoryIds) {
        const { data } = await uniCloud.database().collection('jl_product_categories')
          .doc(id)
          .field('name')
          .get()
        names.push(data[0]?.name || '未知分类')
      }
      return names
    },
    selectionChange(e) {
      this.selectedIds = e.detail.index
    }
  }
}
</script>

<style lang="scss" scoped>
/* 顶部样式保持不变 */
.uni-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  background-color: #f8f8f8;
  border-bottom: 1px solid #eee;
}
.uni-group {
  display: flex;
  align-items: center;
}
.uni-title {
  font-size: 24rpx;
  font-weight: bold;
}
.uni-sub-title {
  font-size: 18rpx;
  color: #999;
  margin-left: 10rpx;
}
.uni-search {
  width: 200rpx;
  margin-right: 10rpx;
}
.uni-button {
  margin-right: 10rpx;
}
/* 新增容器样式 */
.uni-container {
  padding: 20rpx;
}
uni-table {
  margin-top: 20rpx;
}
uni-td {
  padding: 15rpx;
}
</style>